import uuid
from flask import Flask, render_template, redirect, request, url_for, flash
from flask_login import LoginManager, current_user, login_required
from config import Config
from models import db, User, Movie, Cinema, Show, Order  # 导入所有模型
from auth import auth_bp
from blueprints.home import home_bp
from flask_login import current_user
from models import Order

app = Flask(__name__)
app.config.from_object(Config)

# 初始化扩展
db.init_app(app)

# 注册蓝图
app.register_blueprint(auth_bp, url_prefix='/auth')
app.register_blueprint(home_bp)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'auth.login'

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/movies')
def movie_list():
    # 获取所有电影场次
    shows = Show.query.all()
    
    # 为每个场次获取电影和影院信息
    show_details = []
    for show in shows:
        movie = Movie.query.get(show.movie_id)
        cinema = Cinema.query.get(show.cinema_id)
        show_details.append({
            'id': show.id,
            'movie_title': movie.title,
            'cinema_name': cinema.name,
            'cinema_id': cinema.id,
            'start_time': show.start_time,
            'hall': show.hall,
            'price': show.price,
            'available_seats': show.available_seats
        })
    
    return render_template('movie_list.html', shows=show_details)

@app.route('/cinemas')
def cinema_list():
    cinema_id = request.args.get('cinema_id', type=int)
    
    # 获取所有影院
    cinemas = Cinema.query.all()
    
    # 获取所有场次
    if cinema_id:
        shows = Show.query.filter_by(cinema_id=cinema_id).all()
    else:
        shows = Show.query.all()
    
    # 获取所有电影
    movies = Movie.query.all()
    
    return render_template('cinema_list.html', 
                           cinemas=cinemas, 
                           shows=shows, 
                           movies=movies,
                           selected_cinema_id=cinema_id)

@app.route('/booking/<int:show_id>', methods=['GET', 'POST'])
@login_required
def booking(show_id):
    from forms import SeatSelectionForm
    
    form = SeatSelectionForm()
    show = Show.query.get_or_404(show_id)
    movie = Movie.query.get(show.movie_id)
    cinema = Cinema.query.get(show.cinema_id)
    
    # 获取该场次已预订的座位
    orders = Order.query.filter_by(show_id=show_id).all()
    booked_seats = []
    for order in orders:
        seats = order.seats.split(',')
        booked_seats.extend(seats)
    
    # 预设影厅座位布局（10行10列）
    rows = 10
    cols = 10
    row_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
    
    if form.validate_on_submit():
        selected_seats = form.seats.data.split(',')
        total_price = len(selected_seats) * float(show.price)
        payment_method = form.payment_method.data
        
        # 创建新订单
        new_order = Order(
            user_id=current_user.id,
            show_id=show_id,
            seats=form.seats.data,
            total_price=total_price,
            status='paid',
            payment_method=payment_method,
        )
        
        db.session.add(new_order)
        db.session.commit()
        
        flash('订单创建成功！', 'success')
        return redirect(url_for('order_confirmation', order_id=new_order.id))
    
    return render_template('booking.html', 
                           form=form,
                           movie=movie, 
                           cinema=cinema, 
                           show=show, 
                           booked_seats=booked_seats, 
                           rows=rows, 
                           cols=cols,
                           row_letters=row_letters)  

@app.route('/order/<int:order_id>')
@login_required
def order_confirmation(order_id):
    order = Order.query.get_or_404(order_id)
    return render_template('order_confirmation.html', order=order)

@app.route('/seat')
def seat():
    # 获取所有电影场次
    shows = Show.query.all()
    
    # 为每个场次获取电影和影院信息
    show_details = []
    for show in shows:
        movie = Movie.query.get(show.movie_id)
        cinema = Cinema.query.get(show.cinema_id)
        show_details.append({
            'id': show.id,
            'movie_title': movie.title,
            'cinema_name': cinema.name,
            'cinema_id': cinema.id,
            'start_time': show.start_time,
            'end_time': show.end_time,
            'hall': show.hall,
            'price': show.price,
            'available_seats': show.available_seats
        })
    
    return render_template('seat.html', shows=show_details)

# 添加用户个人中心路由
@app.route('/profile')
@login_required
def profile():
    return render_template('profile.html')

# 添加我的订单路由
@app.route('/orders')
@login_required
def orders():
    # 获取用户的所有订单
    orders = Order.query.filter_by(user_id=current_user.id).all()
    return render_template('orders.html', orders=orders)
# 添加订单详情路由
@app.route('/order/<int:order_id>')
@login_required
def order_details(order_id):
    order = Order.query.get_or_404(order_id)
    # 确保订单属于当前用户
    if order.user_id != current_user.id:
        flash('您无权查看此订单', 'danger')
        return redirect(url_for('profile'))
    return render_template('order_details.html', order=order)

# 添加取消订单路由
@app.route('/order/cancel/<int:order_id>', methods=['POST'])
@login_required
def cancel_order(order_id):
    order = Order.query.get_or_404(order_id)
    if order.user_id != current_user.id:
        flash('您无权操作此订单', 'danger')
        return redirect(url_for('profile'))
    
    # 检查订单是否可以取消（例如在开场前2小时）
    from datetime import datetime, timedelta
    if order.show.start_time < datetime.now() + timedelta(hours=2):
        flash('距离电影开场不足2小时，无法取消订单', 'danger')
        return redirect(url_for('order_details', order_id=order.id))
    
    order.status = 'canceled'
    db.session.commit()
    flash('订单已成功取消', 'success')
    return redirect(url_for('order_details', order_id=order.id))

# 添加编辑个人资料路由
@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    from forms import EditProfileForm
    form = EditProfileForm(obj=current_user)
    
    if form.validate_on_submit():
        # 检查用户名是否已存在（除了自己）
        existing_user = User.query.filter(User.username == form.username.data, User.id != current_user.id).first()
        if existing_user:
            flash('用户名已存在', 'danger')
            return redirect(url_for('edit_profile'))
        
        # 更新用户信息
        current_user.username = form.username.data
        current_user.email = form.email.data
        current_user.phone = form.phone.data
        
        # 如果填写了密码，则更新密码
        if form.password.data:
            current_user.set_password(form.password.data)
        
        db.session.commit()
        flash('个人资料已更新', 'success')
        return redirect(url_for('profile'))
    
    return render_template('edit_profile.html', form=form)

@app.route('/movie/<int:movie_id>')
def movie_detail(movie_id):
    movie = Movie.query.get_or_404(movie_id)
    
    # 查询与该电影相关的所有影院和场次信息
    cinemas = Cinema.query.all()
    cinema_shows = {}
    
    for cinema in cinemas:
        shows = Show.query.filter_by(movie_id=movie_id, cinema_id=cinema.id).all()
        if shows:
            cinema_shows[cinema.id] = {
                'name': cinema.name,
                'address': cinema.address,
                'shows': shows
            }
    
    return render_template('movie_detail.html', movie=movie, cinemas=cinema_shows)
    
if __name__ == '__main__':
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_ECHO'] = True
    with app.app_context():
        db.create_all()
    app.run(debug=True, port=5000)